# -*- coding: utf-8 -*-
import logging
from time import sleep
from functools import wraps

import py_global

logger = logging.getLogger(__name__)

max_retries = 0


def retry(func):
    """
    装饰器：函数执行异常重试
    """

    @wraps(func)
    def wrapper(*args, **kwargs):
        retry_times = max_retries
        # 使用do-while循环
        while True:
            logger.info(f'run func:{func.__name__},args:{args},kwargs:{kwargs},retry_times:{retry_times}.')
            try:
                func(*args, **kwargs)
                # 函数执行成功，重试次数归零
                retry_times = 0
            except Exception as e:
                logger.exception(f'run func:{func.__name__},retry_times:{retry_times},error:{repr(e)}')

            if retry_times <= 0:  # 循环次数大于等于零才继续循环，否则中断循环
                break

            retry_times -= 1  # 循环次数减一
            sleep(1)

    return wrapper


@retry
def test_func(arg):
    return 1 / arg


if __name__ == '__main__':
    test_func(1)
    test_func(0)
